package guoanmaker.operator.business.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import guoanmaker.operator.business.model.OperatorCity;
import guoanmaker.operator.business.model.OperatorRefuseRecord;
import guoanmaker.operator.business.model.ProvideCity;
import guoanmaker.operator.business.model.ProvideCommodity;
import guoanmaker.operator.business.model.ProvideCommodityServiceRange;
import guoanmaker.operator.business.modelnobind.OperatorCommodityRo;
import guoanmaker.operator.business.modelnobind.ProvideOrderFormForOrder;
import guoanmaker.operator.business.modelnobind.CommodityRo;
import guoanmaker.operator.business.repository.OperatorCityRepository;
import guoanmaker.operator.business.repository.OperatorRefuseRecordRepository;
import guoanmaker.operator.business.repository.ProvideCityRepository;
import guoanmaker.operator.business.repository.ProvideCommodityRepository;
import guoanmaker.operator.business.repository.ProvideCommodityServiceRangeRepository;

@Repository
public class OperatorCommodityDao {
	
	@PersistenceContext
	EntityManager em;
	
	@Autowired
	private OperatorRefuseRecordRepository operatorRefuseRecordRepository;
	
	@Autowired
	private ProvideCommodityRepository  provideCommodityRepository;
	
	@Autowired
	private ProvideCommodityServiceRangeRepository  provideCommodityServiceRangeRepository;
	
	@Autowired
	private ProvideCityRepository provideCityRepository;
	
	@Autowired
	private OperatorCityRepository operatorCityRepository;
	
	
	/** 
	 * 去掉重复字符串 
	 * @param str 
	 * @return String  
	 * */  
	public static  String removeSameString(String str){    
	    Set<String> mLinkedSet = new LinkedHashSet<String>();    
	    String[] strArray = str.split(",");    
	    StringBuffer sb = new StringBuffer();    
	    for (int i = 0; i < strArray.length; i++)    
	    {    
	        if (!mLinkedSet.contains(strArray[i]))    
	        {    
	            mLinkedSet.add(strArray[i]);    
	            sb.append(strArray[i] + " ");    
	        }else{  
	  //          System.out.println("重复字符:"+strArray[i]);  
	        }    
	    }    
//	    System.out.println(mLinkedSet);    
	    return sb.toString().substring(0, sb.toString().length() - 1);    
	}   
	
	public  Map<String,Object>  selectCommodity(Integer page,Integer size,Integer status,String category,Double startPrice,Double endPrice,String commdittyName,String busname,String commodityCode){
		String jpql="";
		jpql="select new guoanmaker.operator.business.modelnobind.OperatorCommodityRo"
				+ "(p.id,p.commodityName,p.commodityPrice,p.commodity_smallimage,p.commodityState,p.createTime,p.releaseTime,b.businessName,s.serverName,p.salesVolume,p.reasoncontent,p.finalPrice,p.commodityCode)"
				+ " from ProvideCommodity p "
				+ "left join p.providerBusiness b left join  p.serviceType s  where 1=1";
		if(status!=null){
			if(status==1){
				jpql+=" and p.commodityState=1";
			}else if(status==2){
				jpql+=" and p.commodityState=2";
			}else if(status==3){
				jpql+=" and p.commodityState=3";
			}else{
				jpql+=" and (p.commodityState=4 or p.commodityState=5 or p.commodityState=7)";
			}	
		}
		if(category!=null&&!category.equals("")){
			jpql+=" and s.serverName like '%"+category+"%'";	
		}
		if(startPrice!=null&&!startPrice.equals("")){
				jpql+=" and p.commodityPrice >='"+startPrice+"'";
			}
	   if(endPrice!=null&&!endPrice.equals("")){
	        	jpql+=" and p.commodityPrice <='"+endPrice+"'";
	       }
		if(commdittyName!=null&&!commdittyName.equals("")){
			jpql+=" and p.commodityName like '%"+commdittyName+"%'";	
		}
		if(busname!=null&&!busname.equals("")){
			jpql+=" and b.businessName like '%"+busname+"%'";	
		}
		if(commodityCode!=null&&!commodityCode.equals("")){
			jpql+=" and p.commodityCode like '%"+commodityCode+"%'";	
			
		}
		if(status==1||status==2){
			jpql+="order by p.releaseTime desc";
		}else{
			jpql+="order by p.refuseTime desc";
		}
		Query query = em.createQuery(jpql);
		List<OperatorCommodityRo> result = query.getResultList();
		Map<String,Object>  map=new HashMap<>();
		map.put("totle", result.size());
		query.setFirstResult(page*size);
		query.setMaxResults(size);
		List<OperatorCommodityRo> listI =query.getResultList();
		if(status!=null){
			if(status==2){
				for (OperatorCommodityRo operatorCommodityRo : listI) {
					ProvideCommodity provideCommodity=	provideCommodityRepository.findOne(operatorCommodityRo.getId());
					if(provideCommodity!=null){
						String servercity="";
						//isTerritoryRestriction;//是否有地域限制 1:有 2:没有
						if(provideCommodity.getIsTerritoryRestriction()!=null&&!provideCommodity.getIsTerritoryRestriction().equals("")){
							if(provideCommodity.getIsTerritoryRestriction().equals("2")){
    	     					 List<OperatorCity> ops=	operatorCityRepository.findAll();
    	     					 if(ops.size()>0){
    	     						 for (OperatorCity operatorCity : ops) {
    	     							 List<ProvideCity>  provideCity1=provideCityRepository.findByCode(operatorCity.getCityId());
    	     							 if(provideCity1.size()>0){
    	     								 servercity+=provideCity1.get(0).getName()+",";
    	     							 }
    	     						 }
    	     					 }
							}else if(provideCommodity.getIsTerritoryRestriction().equals("1")){
								List<ProvideCommodityServiceRange>  pcs=provideCommodityServiceRangeRepository.selectByServerArea(provideCommodity.getId());
   	     					    if(pcs.size()>0){
   	     						 for (ProvideCommodityServiceRange provideCommodityServiceRange : pcs) {
   	     							 ProvideCity  city=	 provideCityRepository.findOne(provideCommodityServiceRange.getCity().getId());
   	     							 servercity+=city.getName()+",";
									}
   	     					 }
							}
						}
						String c=removeSameString(servercity);
						operatorCommodityRo.setServicecity(c);
						
					}
				}
			}else if(status==3){
				for (OperatorCommodityRo operatorCommodityRo : listI) {
					List<OperatorRefuseRecord> operatorRefuseRecord=operatorRefuseRecordRepository.selectByRecordforBus2(operatorCommodityRo.getId());
					if(operatorRefuseRecord.size()>0){
						operatorCommodityRo.setReasonName(operatorRefuseRecord.get(0).getReasonName());
						operatorCommodityRo.setRefuseTime(operatorRefuseRecord.get(0).getRefuseTime());
					}
				}
			}else if(status==4){
				for (OperatorCommodityRo operatorCommodityRo : listI) {
					List<OperatorRefuseRecord> operatorRefuseRecord=operatorRefuseRecordRepository.selectByRecordforBus3(operatorCommodityRo.getId());
					if(operatorRefuseRecord.size()>0){
						operatorCommodityRo.setReasonName(operatorRefuseRecord.get(0).getReasonName());
						operatorCommodityRo.setRefuseTime(operatorRefuseRecord.get(0).getRefuseTime());
					}
				}
			}
		}
		map.put("result", listI);
		return   map;
	};
	public  Map<String,Object>   selectCommodityNoCondition(Integer page,Integer size,Integer status){
		String jpql="";
		jpql="select new guoanmaker.operator.business.modelnobind.OperatorCommodityRo(p.id,p.commodityName,p.commodityPrice,p.commodityState,"
				+ "p.createTime,b.businessName,s.serverName,reasonName,refuseTime,p.releaseTime,p.salesVolume) from ProvideCommodity p left join p.serviceType s left join p.providerBusiness b where"
				+ "p.serviceType.id=s.id and b.id=p.providerBusiness.id";
		if(status==1){
			jpql="and p.commodityState=1";
		}else if(status==2){
			jpql="and p.commodityState=3";
		}else if(status==3){
			jpql="and p.commodityState=2";
		}else{
			jpql="and p.commodityState=4";
		}
		Query query = em.createQuery(jpql);
		List<OperatorCommodityRo> result = query.getResultList();
		Map<String,Object>  map=new HashMap<>();
		map.put("totle", result.size());
		
		query.setFirstResult(page*size);
		query.setMaxResults(size);
		List<OperatorCommodityRo> listI =query.getResultList();
		if(status==2){
			for (OperatorCommodityRo operatorCommodityRo : listI) {
				List<OperatorRefuseRecord> operatorRefuseRecord=operatorRefuseRecordRepository.selectByRecordforBus2(operatorCommodityRo.getId());
				if(operatorRefuseRecord.size()>0){
					operatorCommodityRo.setReasonName(operatorRefuseRecord.get(0).getReasonName());
					operatorCommodityRo.setRefuseTime(operatorRefuseRecord.get(0).getRefuseTime());
				}
			}
		}else if(status==3){
			for (OperatorCommodityRo operatorCommodityRo : listI) {
				ProvideCommodity provideCommodity=	provideCommodityRepository.findOne(operatorCommodityRo.getId());
				if(provideCommodity!=null){
					operatorCommodityRo.setSalesVolume(provideCommodity.getSalesVolume());
				}
			}
		}else if(status==4){
			for (OperatorCommodityRo operatorCommodityRo : listI) {
				List<OperatorRefuseRecord> operatorRefuseRecord=operatorRefuseRecordRepository.selectByRecordforBus3(operatorCommodityRo.getId());
				if(operatorRefuseRecord.size()>0){
					operatorCommodityRo.setReasonName(operatorRefuseRecord.get(0).getReasonName());
					operatorCommodityRo.setRefuseTime(operatorRefuseRecord.get(0).getRefuseTime());
				}
			}
		}
		map.put("result", listI);
		return   map;
	};
	
	
	public  CommodityRo  selectBycommdityinfo(String id){
		String jpql="select new guoanmaker.operator.business.modelnobind.CommodityRo(p.commodityName,p.isBargaining,p.startingPrice,p.invoiceMail,"
			+"p.isTerritoryRestriction,p.isPromotion,p.commodityCode,p.commodityPrice,"
			+"p.commodityPricePromotion, p.startTime, p.endTime,p.commodity_bigimage,"
			+"p.commodity_smallimage,p.description,p.commodityState,p.createTime,p.createName,"
			+"p.releaseTime, p.stock,p.populationRestriction, p.registrationStartTime,"
			+"p.registrationEndTime,p.synopsis,p.type,p.clickRate,p.introduce,p.process,"
			+"p.promise,p.commodityCase,p.auditOpinion,p.finalPrice,p.reasonName,"
			+"p.refuseTime,p.reasoncontent,p.salesVolume,p.readState) from ProvideCommodity p where p.id='" + id + "'";
		Query query = em.createQuery(jpql);
		CommodityRo  commodityRo=new CommodityRo();
		List<CommodityRo> result = query.getResultList();
		if (result != null && result.size() > 0) {
			commodityRo = result.get(0);
		}
		return  commodityRo;
	}
	
	
	

}
